package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.BTxnLimitCfgMapper;
import cc.rengu.redp.bizimpl.upmp.dao.BankLevelQuotalManagerMapper;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.MerchantLevelInfo;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.RedpUpmpUtil;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class MerchantGradeQuotaManagetServiceImpl extends ServiceImpl<BTxnLimitCfgMapper, BTxnLimitCfg> implements MerchantGradeQuotaManagetService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpBMchntLevelInfoService mchntLevelInfoService;
    @Autowired
    private IUpmpOrganizationService organizationService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private BankLevelQuotalManagerMapper bankLevelQuotalManagerMapper;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;
    @Autowired
    private  BTxnLimitCfgMapper bTxnLimitCfgMapper;
    @Autowired
    private MerchantGradeQuotaManagetService merchantGradeQuotaManagetService;
    private final String oprMenuId = "30000004";

    private final String oprMenuName = "风险管理:商户限额管理:商户等级限额管理";

    private final String webNextUrl = "/admin/quota/merchantGradeManager/checkMcGradeQuota";

    @Transactional(value = "transactionManager")
    public void batchUploadBankQuotal(ArrayList<BTxnLimitCfg> bankLevelQuotaList,String instId) throws RedpException {
//        User user = AuthContextHolder.findAuthUser();
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(instId);
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "merchantGradeManager:import");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if(checked){
            bankLevelQuotaList.forEach((e)->{
                try {
                    uploadIsChecked(e);
                } catch (RedpException redpException) {
                    redpException.printStackTrace();
                }
            });
        }else {

            bankLevelQuotaList.forEach((e)->{
                try {
                    uploadNotChecked(e);
                } catch (RedpException redpException) {
                    redpException.printStackTrace();
                }
            });
        }
    }

    private void uploadIsChecked(BTxnLimitCfg txnCfginfo) throws RedpException {
//        User user = AuthContextHolder.findAuthUser();
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        String industryType = txnCfginfo.getIndustryType();
        txnCfginfo.setLimitType("01");
        txnCfginfo.setLimitInst(txnCfginfo.getMchntLevelCode());
        //设置数据Id
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
        //      txnCfginfo.setInstId(user.getInstId());

        txnCfginfo.setStatus("N"); //Y 启用 N停用
        txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
        txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
        txnCfginfo.setOprId(user.getOprId());
        txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
        //保存正式表
        saveTxnLimitCfgInfo(txnCfginfo);
        //保存零时表
        saveBizTmp(txnCfginfo,BizOprEnum.OPR_ADD.getType());

    }


    private void uploadNotChecked(BTxnLimitCfg txnCfginfo) throws RedpException {
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        String industryType = txnCfginfo.getIndustryType();
        txnCfginfo.setLimitType("01");
        txnCfginfo.setLimitInst(txnCfginfo.getMchntLevelCode());
        //设置数据Id
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
        //    txnCfginfo.setInstId(user.getInstId());

        txnCfginfo.setStatus("Y"); //Y 启用 N停用
        txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
        txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
        txnCfginfo.setOprId(user.getOprId());
        txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
        //保存正式表
        saveTxnLimitCfgInfo(txnCfginfo);
        //保存历史表
        saveQuotaBizHis(txnCfginfo,null,BizOprEnum.OPR_ADD.getType());
    }


    @Override
    public IPage<BTxnLimitCfg> findByPage(QueryRequest request, BTxnLimitCfg info) {
        try {
            LambdaQueryWrapper<BTxnLimitCfg> queryWrapper = new LambdaQueryWrapper<>();

            queryWrapper.orderByDesc(BTxnLimitCfg::getCreateTime);
            Page<BTxnLimitCfg> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            IPage<BTxnLimitCfg> byPage = this.baseMapper.findByPage(page, queryWrapper, info);

            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String instId = user.getInstId();
            List<BTxnLimitCfg> copy=new ArrayList<>();

            for (BTxnLimitCfg record : byPage.getRecords()) {
                String limitInst = record.getLimitInst();
                record.setMchntLevelCode(limitInst);
                UpmpBMchntLevelInfo mchntLevelInfo = mchntLevelInfoService.getMchntLevelInfo(info.getInstId(),limitInst);
                if(null!=mchntLevelInfo) {
                    record.setMchntLevelName(mchntLevelInfo.getMchntLevelName());
                }
                record.setOprId(record.getOprId());
                record.setInstId(record.getInstId());
                record.setCrtOrgId(record.getCrtOrgId());
                record.setCreateTime(record.getCreateTime());
                record.setAuditStatus(record.getAuditStatus());
                record.setAuditRefuseReason(record.getAuditRefuseReason());
                record.setStatus(record.getStatus());
                record.setNotDiffAcctId(record.getNotDiffAcctId());
                record.setLoanId(record.getLoanId());
                record.setCreditId(record.getCreditId());
                record.setLimitInst(record.getLimitInst());
                record.setMchntLevelCode(record.getLimitInst());
                record.setLimitType(record.getLimitType());
                record.setDayLimitAmt(record.getDayLimitAmt());
                record.setMonthLimitAmt(record.getMonthLimitAmt());
                record.setSingleLimitLoanMaxAmt(record.getSingleLimitLoanMaxAmt());
                record.setDayLimitLoanAmt(record.getDayLimitLoanAmt());
                record.setMonthLimitLoanAmt(record.getMonthLimitLoanAmt());
                record.setSingleLimitCreditMaxAmt(record.getSingleLimitCreditMaxAmt());
                record.setDayLimitCreditAmt(record.getDayLimitCreditAmt());
                record.setMonthLimitCreditAmt(record.getMonthLimitCreditAmt());
                copy.add(record);
            }
            IPage<BTxnLimitCfg> newPage=byPage.setRecords(copy);

            return newPage;
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }
    public BTxnLimitCfg getMcGradeQutaDetail(String mchntLevelCode,String instId) throws RedpException {
        try {
            BTxnLimitCfg txnLimitCfgVo = null;
            List<BTxnLimitCfg> McGraQutaList = new ArrayList<>();

            List<BTxnLimitCfg>  resultListCount = bankLevelQuotalManagerMapper.getMcGradeQutaDetail(mchntLevelCode, instId);


            if (resultListCount.size() == 1) {

                McGraQutaList = mapMcGradeParam(resultListCount);
                txnLimitCfgVo = McGraQutaList.get(0);

            }
            return txnLimitCfgVo;
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }
    @Override
    public List<MerchantLevelInfo> getAddMerLevelInfos(String instId) throws RedpException{
        try {
            return this.baseMapper.getAddMerLevelInfos(instId);
        } catch (Exception e) {
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    public List<BTxnLimitCfg> queryBankGradeQuota(String instId,String mchntLevelCode) throws RedpException {
        try {
            if (StringUtils.isBlank(instId)) {
                throw new RedpException("多法人机构号为空");
            }

            List<BTxnLimitCfg> McGraQutaList = new ArrayList<>();
            List<BTxnLimitCfg> resultListCount = bTxnLimitCfgMapper.queryBankGradeQuota(instId, mchntLevelCode);//01商户等级限额

            if (resultListCount.size() > 0) {

                McGraQutaList = mapMcGradeParam(resultListCount);
            }
            return McGraQutaList;
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }
    @Override
    public void saveMerGradeQuota(BTxnLimitCfg txnCfginfo) throws RedpException {

        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());

        //设置数据Id
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
        txnCfginfo.setLimitType("01");//01-商户等级限额
        txnCfginfo.setLimitInst(txnCfginfo.getMchntLevelCode());
        String instId = "";
        if(user.isAdmin()){
            instId = txnCfginfo.getInstId();
            UpmpOrganization headOrg = organizationService.getHeadOrgByCode(instId);
            String crtOrgId = headOrg == null ? user.getOrgCode() : headOrg.getOrgCode();
            txnCfginfo.setInstId(instId);
            txnCfginfo.setCrtOrgId(crtOrgId);
        }else {
            instId = user.getInstId();
            txnCfginfo.setInstId(instId);
            txnCfginfo.setCrtOrgId(org.getOrgCode());
        }
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantGradeManager:view");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if(checked){

            txnCfginfo.setStatus("N");
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());//"01"新增待审核 02-新增审核通过
            txnCfginfo.setOprId(user.getId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            saveTxnLimitCfgInfo(txnCfginfo);
            //保存零时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_ADD.getType());
        }else {
            txnCfginfo.setStatus("Y"); //Y 启用 N停用
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());//"01"新增待审核 02-新增审核通过
            txnCfginfo.setOprId(user.getId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            saveTxnLimitCfgInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo,null,BizOprEnum.OPR_ADD.getType());

        }

    }


    @Override
    public void editMerGradeQuota(BTxnLimitCfg txnCfginfo) throws RedpException {
        String mchntLevelCode = txnCfginfo.getMchntLevelCode();
        if(StringUtils.isBlank(mchntLevelCode)){
            throw new RedpException("请求数据有误");
        }
        txnCfginfo.setLimitInst(txnCfginfo.getMchntLevelCode());
        txnCfginfo.setLimitType("01");//商户等级限额
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantGradeManager:view");

        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        BTxnLimitCfg oldData = getMcGradeQuotaDetail(txnCfginfo);
        txnCfginfo.setStatus(oldData.getStatus()); //Y 启用 N停用
        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if(checked){

            //txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType()); //41-修改待审42-修改审核通过
            txnCfginfo.setLastOprId(user.getId());
            txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

            //修正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo,BizOprEnum.OPR_UPDATE.getType());
        }else {

            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
            txnCfginfo.setOprId(user.getId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            updateTxnLimitCfgInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo,oldData,BizOprEnum.OPR_UPDATE.getType());
        }

    }

    @Override
    public void startMcGradeQuota(BTxnLimitCfg req) throws RedpException {
        BTxnLimitCfg txnCfginfo = getMcGradeQuotaDetail(req);
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantGradeManager:view");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        BTxnLimitCfg oldData = new BTxnLimitCfg();
        BeanUtils.copyProperties(txnCfginfo,oldData);

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());

        txnCfginfo.setLastOprId(user.getId());
        txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

        if(checked){

            //txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());

            //修正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo,BizOprEnum.OPR_USE.getType());
        }else {
            txnCfginfo.setStatus("Y"); //Y 启用 N停用
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());           //保存正式表
            updateTxnLimitCfgInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo,oldData,BizOprEnum.OPR_USE.getType());
        }
    }

    @Override
    public void stopMcGradeQuota(BTxnLimitCfg req) throws RedpException {
        BTxnLimitCfg txnCfginfo = getMcGradeQuotaDetail(req);
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantGradeManager:view");

        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        BTxnLimitCfg oldData = new BTxnLimitCfg();
        BeanUtils.copyProperties(txnCfginfo,oldData);
        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());

        txnCfginfo.setLastOprId(user.getId());
        txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

        if(checked){

            //txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());

            //修正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo,BizOprEnum.OPR_STOP.getType());
        }else {
            txnCfginfo.setStatus("N");
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
            //保存正式表
            updateTxnLimitCfgInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo,oldData,BizOprEnum.OPR_STOP.getType());
        }
    }

    @Override
    public void deleteMcGradeQuota(BTxnLimitCfg req) throws RedpException {

        BTxnLimitCfg txnCfginfo = getMcGradeQuotaDetail(req);
        List<UpmpBMchntBaseInfo> mcInfos = bMchntBaseInfoService.getMarchantInfoByLevel(txnCfginfo.getLimitInst());
        if(mcInfos.size()>0){
            throw new RedpException("该商户等级正在使用不能注销");
        }
        BTxnLimitCfg oldData = new BTxnLimitCfg();
        BeanUtils.copyProperties(txnCfginfo,oldData);

        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantGradeManager:view");

        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());

        txnCfginfo.setLastOprId(user.getId());
        txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

        if(checked){

            //txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());

            //修正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo,BizOprEnum.OPR_CANCEL.getType());
        }else {
            txnCfginfo.setStatus("N");
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());            //保存正式表
            updateTxnLimitCfgInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo,oldData,BizOprEnum.OPR_CANCEL.getType());
        }
    }



    private void saveTxnLimitCfgInfo(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {
            String limitType = txnCfginfo.getLimitType();
            String instId = txnCfginfo.getInstId();
            String limitInst = txnCfginfo.getLimitInst();
            if(StringUtils.isBlank(limitType)||StringUtils.isBlank(instId)||StringUtils.isBlank(limitInst)){
                log.error("请求数据有误:[{"+limitType+"|"+instId+"|"+limitInst+"}]");
                throw new RedpException("请求数据有误:"+limitType+"|"+instId+"|"+limitInst);
            }

            List resultListCount =this.baseMapper.selectLimitInst(limitType,limitInst,instId);

            if (resultListCount.size() > 0) {
                log.error("限额信息已存在:[{"+txnCfginfo.getLimitInst()+"}]");
                throw new RedpException(txnCfginfo.getLimitInst() + "限额信息已存在");
            }

            //限额
            BTxnLimitCfg queryMC= new BTxnLimitCfg();
            queryMC.setInstId(txnCfginfo.getInstId());
            queryMC.setLimitType(txnCfginfo.getLimitType());
            queryMC.setLimitInst(txnCfginfo.getLimitInst());
            queryMC.setLimitAcctType("*");//"*" 不分账户类型
            queryMC.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitMaxAmt());
            queryMC.setDayLimitAmt(txnCfginfo.getDayLimitAmt());
            queryMC.setMonthLimitAmt(txnCfginfo.getMonthLimitAmt());
            queryMC.setStatus(txnCfginfo.getStatus());
            queryMC.setAuditStatus(txnCfginfo.getAuditStatus());
            queryMC.setOprId(txnCfginfo.getOprId());
            queryMC.setCrtOrgId(txnCfginfo.getCrtOrgId());
            queryMC.setCreateTime(txnCfginfo.getCreateTime());
            queryMC.setId(txnCfginfo.getNotDiffAcctId());
            this.save(queryMC);


            //借记限额
            BTxnLimitCfg queryLoa= new BTxnLimitCfg();
            queryLoa.setInstId(txnCfginfo.getInstId());
            queryLoa.setLimitType(txnCfginfo.getLimitType());
            queryLoa.setLimitInst(txnCfginfo.getLimitInst());
            queryLoa.setLimitAcctType("20");//20-借记账户(包括本行、他行借记账户)  21-贷记账户(包括本行、他行贷记账户)
            queryLoa.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
            queryLoa.setDayLimitAmt(txnCfginfo.getDayLimitLoanAmt());
            queryLoa.setMonthLimitAmt(txnCfginfo.getMonthLimitLoanAmt());
            queryLoa.setStatus(txnCfginfo.getStatus());
            queryLoa.setAuditStatus(txnCfginfo.getAuditStatus());
            queryLoa.setOprId(txnCfginfo.getOprId());
            queryLoa.setCrtOrgId(txnCfginfo.getCrtOrgId());
            queryLoa.setCreateTime(txnCfginfo.getCreateTime());
            queryLoa.setId(txnCfginfo.getLoanId());
            this.save(queryLoa);

            //贷记限额
            BTxnLimitCfg queryCre= new BTxnLimitCfg();
            queryCre.setInstId(txnCfginfo.getInstId());
            queryCre.setLimitType(txnCfginfo.getLimitType());
            queryCre.setLimitInst(txnCfginfo.getLimitInst());
            queryCre.setLimitAcctType("21");//20-借记账户(包括本行、他行借记账户)  21-贷记账户(包括本行、他行贷记账户)
            queryCre.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
            queryCre.setDayLimitAmt(txnCfginfo.getDayLimitCreditAmt());
            queryCre.setMonthLimitAmt(txnCfginfo.getMonthLimitCreditAmt());
            queryCre.setStatus(txnCfginfo.getStatus());
            queryCre.setAuditStatus(txnCfginfo.getAuditStatus());
            queryCre.setOprId(txnCfginfo.getOprId());
            queryCre.setCrtOrgId(txnCfginfo.getCrtOrgId());
            queryCre.setCreateTime(txnCfginfo.getCreateTime());
            queryCre.setId(txnCfginfo.getCreditId());
            this.save(queryCre);

        } catch (Exception e) {
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    //保存临时表
    private void saveBizTmp(BTxnLimitCfg txnCfginfo,String oprType) throws RedpException {
        //主记录key
        String uuid = CommonUtils.getUUID();
        if(StringUtils.isNotBlank(oprType)&& !(BizOprEnum.OPR_ADD.getType().equals(oprType))){
            BizTmp tmp = bizTmpService.getBizTmpDetail(txnCfginfo.getNotDiffAcctId());

            if(null !=tmp && StringUtils.isNotBlank(tmp.getMasterKey())){
                String masterKey = tmp.getMasterKey();
                uuid=masterKey;
            }

        }
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());

        List<BTxnLimitCfg> TxnDatalist = coverBizData(txnCfginfo);
        List<BizTmp> bizTmpList = new ArrayList<>();
        for (BTxnLimitCfg txnLimitCfg : TxnDatalist) {
            BizTmp tmp = coverBizTmp(txnLimitCfg, oprType, oprMenuId, oprMenuName, org.getOrgCode(), user.getInstId(), txnCfginfo.getBizStatus(), txnLimitCfg.getAuditStatus(), webNextUrl);
            String bizData = JSON.toJSONString(txnLimitCfg);
            if (bizData.length() > 12000) {
                throw new RedpException("业务数据过长，请联系管理员！");
            }
            String bizData1;
            String bizData2 = "";
            String bizData3 = "";
            if (bizData.length() > 4000) {
                bizData1 = bizData.substring(0, 3999);
                bizData2 = bizData.substring(4000);
            } else {
                bizData1 = bizData;
            }
            if (bizData2.length() > 4000) {
                bizData2 = bizData2.substring(0, 3999);
                bizData3 = bizData.substring(8000);
            }
            tmp.setBizData1(bizData1);
            tmp.setBizData2(bizData2);
            tmp.setBizData3(bizData3);
            tmp.setMchntNo(null);
            tmp.setMchntName(null);
            tmp.setTermNo(null);
            tmp.setDetailFlag("Y");
            tmp.setMasterKey(uuid);
            tmp.setRealId(txnLimitCfg.getId());
            bizTmpList.add(tmp);
        }
        BizTmp bizTmp = coverBizTmp(TxnDatalist.get(0), oprType, oprMenuId, oprMenuName, org.getOrgCode(), user.getInstId(), txnCfginfo.getBizStatus(), txnCfginfo.getAuditStatus(), webNextUrl);
        bizTmp.setBizData1("明细有" + bizTmpList.size() + "条");
        bizTmp.setMchntNo(null);
        bizTmp.setMchntName(null);
        bizTmp.setTermNo(null);
        bizTmp.setRealId(uuid);
        bizTmp.setDetailFlag("N");
        bizTmpList.add(bizTmp);
        bizTmpService.saveOrUpdateBatch(bizTmpList);
    }

    private List<BTxnLimitCfg> coverBizData(BTxnLimitCfg txnCfginfo) {
        List<BTxnLimitCfg> txnLimitCfgs = new ArrayList<>();
        BTxnLimitCfg notDiff = new BTxnLimitCfg();
        notDiff.setSingleLimitMaxAmt("");
        notDiff.setDayLimitAmt(txnCfginfo.getDayLimitAmt());
        notDiff.setMonthLimitAmt(txnCfginfo.getMonthLimitAmt());

        notDiff.setStatus(txnCfginfo.getStatus());
        notDiff.setAuditStatus(txnCfginfo.getAuditStatus());
        notDiff.setOprId(txnCfginfo.getOprId());
        notDiff.setCreateTime(txnCfginfo.getCreateTime());
        notDiff.setLastOprId(txnCfginfo.getLastOprId());
        notDiff.setLastUpdateTime(txnCfginfo.getLastUpdateTime());

        notDiff.setLimitAcctType("*");
        notDiff.setInstId(txnCfginfo.getInstId());
        notDiff.setLimitType(txnCfginfo.getLimitType());
        notDiff.setLimitInst(txnCfginfo.getLimitInst());
        notDiff.setId(txnCfginfo.getNotDiffAcctId());

        txnLimitCfgs.add(notDiff);

        BTxnLimitCfg credCfg = new BTxnLimitCfg();
        credCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
        credCfg.setDayLimitAmt(txnCfginfo.getDayLimitCreditAmt());
        credCfg.setMonthLimitAmt(txnCfginfo.getMonthLimitCreditAmt());

        credCfg.setStatus(txnCfginfo.getStatus());
        credCfg.setAuditStatus(txnCfginfo.getAuditStatus());
        credCfg.setOprId(txnCfginfo.getOprId());
        credCfg.setCreateTime(txnCfginfo.getCreateTime());
        credCfg.setLastOprId(txnCfginfo.getLastOprId());
        credCfg.setLastUpdateTime(txnCfginfo.getLastUpdateTime());

        credCfg.setLimitAcctType("21");
        credCfg.setInstId(txnCfginfo.getInstId());
        credCfg.setLimitType(txnCfginfo.getLimitType());
        credCfg.setLimitInst(txnCfginfo.getLimitInst());
        credCfg.setId(txnCfginfo.getCreditId());

        txnLimitCfgs.add(credCfg);

        BTxnLimitCfg loanCfg = new BTxnLimitCfg();
        loanCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
        loanCfg.setDayLimitAmt(txnCfginfo.getDayLimitLoanAmt());
        loanCfg.setMonthLimitAmt(txnCfginfo.getMonthLimitLoanAmt());

        loanCfg.setStatus(txnCfginfo.getStatus());
        loanCfg.setAuditStatus(txnCfginfo.getAuditStatus());
        loanCfg.setOprId(txnCfginfo.getOprId());
        loanCfg.setCreateTime(txnCfginfo.getCreateTime());
        loanCfg.setLastOprId(txnCfginfo.getLastOprId());
        loanCfg.setLastUpdateTime(txnCfginfo.getLastUpdateTime());

        loanCfg.setLimitAcctType("20");
        loanCfg.setInstId(txnCfginfo.getInstId());
        loanCfg.setLimitType(txnCfginfo.getLimitType());
        loanCfg.setLimitInst(txnCfginfo.getLimitInst());
        loanCfg.setId(txnCfginfo.getLoanId());

        txnLimitCfgs.add(loanCfg);

        return txnLimitCfgs;
    }

    private BizTmp coverBizTmp(BTxnLimitCfg entity, String bizOpr, String menuId, String menuName, String orgCode, String instId, String ruleStatus, String auditStatus, String webNextUrlStr){

        BizTmp bizTmp = new BizTmp();
        String ename = entity.getClass().getAnnotation(TableName.class).value();
        String cname = entity.getClass().getAnnotation(ApiModelProperty.class).value();

        bizTmp.setRealId(entity.getId());
        bizTmp.setBizData1("");
        bizTmp.setBizData2("");
        bizTmp.setBizData3("");
        bizTmp.setBizOpr(bizOpr);
        bizTmp.setOprId(entity.getOprId());
        bizTmp.setCreateTime(entity.getCreateTime());
        bizTmp.setLastOprId(entity.getLastOprId());
        bizTmp.setLastUpdateTime(entity.getLastUpdateTime());
        bizTmp.setOprMenuId(menuId);
        bizTmp.setOprMenuName(menuName);
        bizTmp.setOprTableCname(cname);
        bizTmp.setOprTableEname(ename);
        bizTmp.setManageInstId(orgCode);
        bizTmp.setInstId(instId);
        bizTmp.setBizStatus(ruleStatus);
        bizTmp.setAuditStatus(auditStatus);
        bizTmp.setWebNextUrl(webNextUrlStr);

        return bizTmp;
    }

    private void saveQuotaBizHis(BTxnLimitCfg txnCfginfo,BTxnLimitCfg oldTxnCfginfo,String bizOpr) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        List<BTxnLimitCfg> txnLimitCfgsOld=new ArrayList<>();
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        List<BTxnLimitCfg> txnLimitCfgs = coverBizData(txnCfginfo);
        if(BizOprEnum.OPR_ADD.getType().equals(bizOpr)){
            for (BTxnLimitCfg bean : txnLimitCfgs) {
                txnLimitCfgsOld.add(new BTxnLimitCfg());
            }
        }else {
            txnLimitCfgsOld = coverBizData(oldTxnCfginfo);
        }

        List<String> realIds = new ArrayList<>();
        List<Object> entitys = new ArrayList<>();
        List<String> bizOprs = new ArrayList<>();
        List<Object> entitysOld = new ArrayList<>();
        for (BTxnLimitCfg bean : txnLimitCfgs){
            realIds.add(CommonUtils.getUUID());
            entitys.add(bean);
            bizOprs.add(bizOpr);
        }
        for (BTxnLimitCfg bean : txnLimitCfgsOld) {

            entitysOld.add(bean);

        }
        bizHisService.saveBizHisList(entitys,entitysOld,user,org.getInstId(),bizOprs,
                txnLimitCfgs.get(0).getCreateTime(),oprMenuId,oprMenuName,realIds,null,null,null);

    }


    /**
     * 获取数据详情
     * @param request
     * @return
     */
    public BTxnLimitCfg getMcGradeQuotaDetail(BTxnLimitCfg request) throws RedpException {
        try {
            String notDiffAcctId = request.getNotDiffAcctId();
            String creditId = request.getCreditId();
            String loanId = request.getLoanId();
            if (StringUtils.isBlank(notDiffAcctId) || StringUtils.isBlank(creditId) || StringUtils.isBlank(loanId)) {
                log.error("请求数据有误");
                throw new RedpException("请求数据有误");
            }

            List resultList = this.baseMapper.selectMcGradeQuotaDetail(notDiffAcctId,creditId,loanId);

            if (null == resultList || resultList.size() > 1) {
                throw new RedpException("限额详情数据获取失败");
            }
            List<BTxnLimitCfg> bankQuotaList = mapMcGradeParam(resultList);

            return bankQuotaList.get(0);
        } catch (Exception e) {

            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    private List<BTxnLimitCfg> mapMcGradeParam (List<BTxnLimitCfg> resultList){
        for (BTxnLimitCfg record : resultList) {
            String limitInst = record.getLimitInst();
            record.setMchntLevelCode(limitInst);
            UpmpBMchntLevelInfo mchntLevelInfo = mchntLevelInfoService.getMchntLevelInfo(record.getInstId(),limitInst);
            if(null!=mchntLevelInfo) {
                record.setMchntLevelName(mchntLevelInfo.getMchntLevelName());
            }
            record.setOprId(record.getOprId());
            record.setInstId(record.getInstId());
            record.setCrtOrgId(record.getCrtOrgId());
            record.setCreateTime(record.getCreateTime());
            record.setAuditStatus(record.getAuditStatus());
            record.setAuditRefuseReason(record.getAuditRefuseReason());
            record.setStatus(record.getStatus());
            record.setNotDiffAcctId(record.getNotDiffAcctId());
            record.setLoanId(record.getLoanId());
            record.setCreditId(record.getCreditId());
            record.setLimitInst(record.getLimitInst());
            record.setMchntLevelCode(record.getLimitInst());
            record.setLimitType(record.getLimitType());
            record.setDayLimitAmt(record.getDayLimitAmt());
            record.setMonthLimitAmt(record.getMonthLimitAmt());
            record.setSingleLimitLoanMaxAmt(record.getSingleLimitLoanMaxAmt());
            record.setDayLimitLoanAmt(record.getMonthLimitLoanAmt());
            record.setMonthLimitLoanAmt(record.getMonthLimitLoanAmt());
            record.setSingleLimitCreditMaxAmt(record.getSingleLimitCreditMaxAmt());
            record.setDayLimitCreditAmt(record.getDayLimitCreditAmt());
            record.setMonthLimitCreditAmt(record.getMonthLimitCreditAmt());
        }

        return resultList;
    }

    /**
     * 审核修改
     * @param txnCfginfo
     */
    private void updateTxnLimitCfgAuthStatus(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {

            //不分账户 终端限额
            this.baseMapper.updateTxnLimitCfgAuthById(txnCfginfo.getAuditStatus(), txnCfginfo.getLastOprId(), txnCfginfo.getLastUpdateTime(),
                    txnCfginfo.getAuditRefuseReason(), txnCfginfo.getNotDiffAcctId());

            //贷记
            this.baseMapper.updateTxnLimitCfgAuthById(txnCfginfo.getAuditStatus(), txnCfginfo.getLastOprId(), txnCfginfo.getLastUpdateTime(),
                    txnCfginfo.getAuditRefuseReason(), txnCfginfo.getCreditId());

            //借记
            this.baseMapper.updateTxnLimitCfgAuthById(txnCfginfo.getAuditStatus(), txnCfginfo.getLastOprId(), txnCfginfo.getLastUpdateTime(),
                    txnCfginfo.getAuditRefuseReason(), txnCfginfo.getLoanId());

        } catch (Exception e) {
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    private void updateTxnLimitCfgInfo(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {

            //不分账户 终端限额
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("id", txnCfginfo.getNotDiffAcctId());
            bTxnLimitCfgMapper.update(txnCfginfo, queryWrapper);
//            this.baseMapper.updateTxnLimitCfgAuthById(txnCfginfo.getAuditStatus(), txnCfginfo.getLastOprId(), txnCfginfo.getLastUpdateTime(),
//                    txnCfginfo.getAuditRefuseReason(), txnCfginfo.getNotDiffAcctId());

            //贷记
           // BTxnLimitCfg creditBtxn=new BTxnLimitCfg();
            txnCfginfo.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
            txnCfginfo.setDayLimitAmt(txnCfginfo.getDayLimitCreditAmt());
            txnCfginfo.setMonthLimitAmt(txnCfginfo.getMonthLimitCreditAmt());
            queryWrapper.clear();
            queryWrapper.eq("id", txnCfginfo.getCreditId());
            bTxnLimitCfgMapper.update(txnCfginfo, queryWrapper);
//            this.baseMapper.updateTxnLimitCfgAuthById(txnCfginfo.getAuditStatus(), txnCfginfo.getLastOprId(), txnCfginfo.getLastUpdateTime(),
//                    txnCfginfo.getAuditRefuseReason(), txnCfginfo.getCreditId());

            //借记
            BTxnLimitCfg loanBtxn=new BTxnLimitCfg();
            txnCfginfo.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
            txnCfginfo.setDayLimitAmt(txnCfginfo.getDayLimitLoanAmt());
            txnCfginfo.setMonthLimitAmt(txnCfginfo.getMonthLimitLoanAmt());
            queryWrapper.clear();
            queryWrapper.eq("id", txnCfginfo.getLoanId());
            bTxnLimitCfgMapper.update(txnCfginfo, queryWrapper);
//            this.baseMapper.updateTxnLimitCfgAuthById(txnCfginfo.getAuditStatus(), txnCfginfo.getLastOprId(), txnCfginfo.getLastUpdateTime(),
//                    txnCfginfo.getAuditRefuseReason(), txnCfginfo.getLoanId());
        } catch (Exception e) {
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }
}
